package co.gov.medellin.sdep.sisdep.model.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.object.MappingSqlQuery;
import org.springframework.jdbc.object.SqlUpdate;

import co.gov.medellin.sdep.sisdep.model.Citacion;
import co.gov.medellin.sdep.sisdep.model.Comparendo;
import co.gov.medellin.sdep.sisdep.model.dao.CitacionDAOImpl.ValidarDocumentoOperation;
import co.gov.medellin.sdep.sisdep.model.dao.CitacionDAOImpl.VerificarDocumentoQuery;
import co.gov.medellin.sdep.sisdep.model.dao.FeriaDecFormVentaDAOImpl.ListaDistribucionQueryOperation;
import co.gov.medellin.sdep.sisdep.model.dao.FeriaDecFormVentaDAOImpl.ListaDistribuciones;

public class ComparendoDAOImpl extends JdbcDaoSupport implements IComparendoDAO {

    private InsertOperation insertOperation;

    private UpdateOperation updateOperation;

    private DeleteOperation deleteOperation;

    private DeleteByPrimaryKey deleteByPrimaryKey;

    private FindByPrimaryKeyQuery findByPrimaryKeyQuery;

    private FindByCriteriaQuery findByCriteriaQuery;

    private FindAllQuery findAllQuery;
    
    private FindByRadicadoQuery findByRadicadoQuery;
    
    public ListaInfracciones listaInfracciones;

    private VerificarDocumentoQuery verificarDocumentoQuery;
    
    private FindByActiveStateQuery findByActiveStateQuery;

	private static final String SELECT = "SELECT * FROM OPE_COMPARENDO_T ";
	private static final String WHERE = " WHERE ";
	private static final String PARAMETER = " ?, ";

    public void delete(Comparendo comparendo) {
		deleteOperation.execute( comparendo  );
	}

	public void deleteByPrimaryKey(long id) {
		deleteByPrimaryKey.execute(id);
	}

	public Comparendo findByPrimaryKey(long login) {
		return findByPrimaryKeyQuery.runQuery(login);
	}

	public void insert(Comparendo comparendo) {
		insertOperation.execute( comparendo );
	}

	public void update(Comparendo comparendo) {
		updateOperation.execute( comparendo );
	}

	public Comparendo findByCriteria(Comparendo  comparendo) {
		return findByCriteriaQuery.runQuery(comparendo);
	}

	public List load() {
		return findAllQuery.runQuery();
	}
	
	public List loadByRadicado(Comparendo comparendo) {
		return findByRadicadoQuery.runQuery(comparendo);
	}
	
	public List listaInfracciones() {
		return listaInfracciones.runQuery();
	}

	public String verificarDocumento(Comparendo  comparendo) {
		return verificarDocumentoQuery.runQuery(comparendo);
	}
	
	public Comparendo findByActiveState(Comparendo  comparendo) {
		return findByActiveStateQuery.runQuery(comparendo);
	}

	public void initDao() {
    	insertOperation   = new InsertOperation( getDataSource() );
    	updateOperation = new UpdateOperation(  getDataSource() );
    	//deleteOperation = new DeleteOperation(  getDataSource() );
    	//deleteByPrimaryKey = new DeleteByPrimaryKey( getDataSource());
    	//findByPrimaryKeyQuery   = new FindByPrimaryKeyQuery(  getDataSource() );
    	//findByCriteriaQuery = new FindByCriteriaQuery(  getDataSource() );
    	findAllQuery = new FindAllQuery( getDataSource() );
    	findByRadicadoQuery = new FindByRadicadoQuery( getDataSource() );
    	listaInfracciones = new ListaInfracciones(getDataSource() );
    	verificarDocumentoQuery = new VerificarDocumentoQuery(getDataSource() );
    	//findByActiveStateQuery = new FindByActiveStateQuery( getDataSource() );
    }

    // ------------- SaveOperation ---------------------------------------
	class InsertOperation extends SqlUpdate	{
		private static final String sql = "INSERT INTO OPE_COMPARENDO_T ("
				  + " ID, "
				  + " ID_COMPARENDO_ENTIDAD, "
				  + " ID_TIPO_INFRACCION, "
				  + " ID_TIPO_INFRACTOR, "
				  + " ID_PERSONA, "
				  + " ID_CITACION, "
				  + " CODIGO, "
				  + " RADICADO, "
				  + " DIRECCION, "
				  + " CODIGO_BARRIO, "
				  + " BARRIO, "
				  + " CODIGO_COMUNA, "
				  + " COMUNA, "
				  + " COBRO_COACTIVO, "
				  + " VALOR_COBRO, "
				  + " ESTADO, "
				  + " USUARIO_CREA, "
				  + " FECHA_CREA "
				  + ") VALUES ("
			  	  + " OPE_COMPARENDO_SEC.nextVal, "
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + "(SELECT ID FROM ADM_PERSONA_T WHERE IDENTIFICACION=? AND ID_TIPO_IDENTIFICACION=?),"
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + "SYSDATE"
				  + ")";
		public  InsertOperation(DataSource ds) {
			super(ds,sql);
			//set here required parameters			
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			compile();
		}
		public void execute(Comparendo comparendo) {
			InsertOperation.this.update( new Object[]{
				comparendo.getIdComparendoEntidad(),
				comparendo.getIdTipoInfraccion(),
				comparendo.getIdTipoInfractor(),
				comparendo.getDocumento(),
				comparendo.getIdTipoDocumentoStr(),
				comparendo.getIdCitacion(),
				comparendo.getCodigo(),
				comparendo.getRadicado(),
				comparendo.getDireccion(),
				comparendo.getCodigoBarrio(),
				comparendo.getBarrio(),
				comparendo.getCodigoComuna(),
				comparendo.getComuna(),
				comparendo.getCobroCoactivo(),
				comparendo.getValorCobro(),
				comparendo.getEstado(),
				comparendo.getUsuarioCrea()				
				});
		}
    }

    // ------------- UpdateOperation -------------------------------------
    class UpdateOperation extends SqlUpdate	{
    	private static final String sql = "UPDATE OPE_COMPARENDO_T SET "					  
					  + " ID_COMPARENDO_ENTIDAD = ? ,"
					  + " ID_TIPO_INFRACCION = ? ,"
					  + " ID_TIPO_INFRACTOR = ? ,"
					  + " ID_PERSONA = (SELECT ID FROM ADM_PERSONA_T WHERE IDENTIFICACION=? AND ID_TIPO_IDENTIFICACION=?) ,"
					  + " ID_CITACION = ? ,"
					  + " CODIGO = ? ,"
					  + " RADICADO = ? ,"
					  + " DIRECCION = ? ,"
					  + " CODIGO_BARRIO = ? ,"
					  + " BARRIO = ? ,"
					  + " CODIGO_COMUNA = ? ,"
					  + " COMUNA = ? ,"
					  + " COBRO_COACTIVO = ? ,"
					  + " VALOR_COBRO = ? ,"
					  + " ESTADO = ?, "					  
					  + " USUARIO_MODIFICA = ? ,"
					  + " FECHA_MODIFICA = SYSDATE"
				  	  + WHERE
				  	  + " ID = ? ";
		public  UpdateOperation(DataSource ds) {
			super(ds,sql);
			//set here required parameters			
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));					
			declareParameter( new SqlParameter(Types.INTEGER));
			compile();
		}
		public void execute(Comparendo comparendo) {
			UpdateOperation.this.update( new Object[]{				
				comparendo.getIdComparendoEntidad(),
				comparendo.getIdTipoInfraccion(),
				comparendo.getIdTipoInfractor(),
				comparendo.getDocumento(),
				comparendo.getIdTipoDocumentoStr(),
				comparendo.getIdCitacion(),
				comparendo.getCodigo(),
				comparendo.getRadicado(),
				comparendo.getDireccion(),
				comparendo.getCodigoBarrio(),
				comparendo.getBarrio(),
				comparendo.getCodigoComuna(),
				comparendo.getComuna(),
				comparendo.getCobroCoactivo(),
				comparendo.getValorCobro(),
				comparendo.getEstado(),				
				comparendo.getUsuarioModifica(),			
				comparendo.getId()
				});
		}
    }

    // ------------- DeleteOperation -------------------------------------
    class DeleteOperation extends SqlUpdate	{
		private static final String sql = "DELETE FROM OPE_COMPARENDO_T "
										+ WHERE
			  	  	  					+ " CODIGO = ? ";
		public DeleteOperation(DataSource ds) {
			super(ds,sql);
			declareParameter( new SqlParameter(Types.CHAR) );
			compile();
		}
		public void execute(Comparendo comparendo) {
			this.update( new Object[]{
				comparendo.getCodigo(),
			});
		}
	}

    // ------------- DeleteByPrimaryKey ----------------------------------
    class DeleteByPrimaryKey extends SqlUpdate	{
		private static final String sql = "DELETE FROM OPE_COMPARENDO_T "
										+ WHERE + "1=1";
		public DeleteByPrimaryKey(DataSource ds) {
			super(ds,sql);
			compile();
		}	
		public void execute(long id) {
			this.update( new Object[]{
			});
		}	
    }

    // ---- BaseQueryOperation for Mapping ResultSet values --------------
	abstract class BaseQueryOperation extends MappingSqlQuery {
		public BaseQueryOperation(DataSource ds,String sql) {
	   		super(ds,sql);
		}	
		protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
			Comparendo comparendo = new Comparendo();
				comparendo.setId(new Long(rs.getLong("ID")));
				comparendo.setIdComparendoEntidad(new Long(rs.getLong("ID_COMPARENDO_ENTIDAD")));
				comparendo.setIdComparendoEntidadStr(rs.getString("ID_COMPARENDO_ENTIDAD"));
				comparendo.setIdTipoInfraccion(new Long(rs.getLong("ID_TIPO_INFRACCION")));
				comparendo.setIdTipoInfraccionStr(rs.getString("ID_TIPO_INFRACCION"));
				comparendo.setIdTipoInfractor(new Long(rs.getLong("ID_TIPO_INFRACTOR")));
				comparendo.setIdTipoInfractorStr(rs.getString("ID_TIPO_INFRACTOR"));
				comparendo.setIdPersona(new Long(rs.getLong("ID_PERSONA")));
				comparendo.setIdCitacion(new Long(rs.getLong("ID_CITACION")));
				comparendo.setCodigo(rs.getString("CODIGO"));
				comparendo.setRadicado(rs.getString("RADICADO"));
				comparendo.setDireccion(rs.getString("DIRECCION"));
				comparendo.setCodigoBarrio(rs.getString("CODIGO_BARRIO"));
				comparendo.setBarrio(rs.getString("BARRIO"));
				comparendo.setCodigoComuna(rs.getString("CODIGO_COMUNA"));
				comparendo.setComuna(rs.getString("COMUNA"));
				comparendo.setCobroCoactivo(rs.getString("COBRO_COACTIVO"));
				comparendo.setValorCobro(new Long(rs.getLong("VALOR_COBRO")));
				comparendo.setValorCobroStr(rs.getString("VALOR_COBRO"));
				comparendo.setEstado(rs.getString("ESTADO"));
				comparendo.setUsuarioCrea(rs.getString("USUARIO_CREA"));
				comparendo.setFechaCrea(rs.getDate("FECHA_CREA"));		
				comparendo.setUsuarioModifica(rs.getString("USUARIO_MODIFICA"));
				comparendo.setFechaModifica(rs.getDate("FECHA_MODIFICA"));		
				comparendo.setDocumento(rs.getString("IDENTIFICACION"));
				comparendo.setIdTipoDocumentoStr(rs.getString("ID_TIPO_IDENTIFICACION"));
				comparendo.setStrComparendoEntidad(rs.getString("COM_ENTIDAD"));
				comparendo.setStrTipoInfractor(rs.getString("INFRACTOR"));
				comparendo.setStrTipoInfraccion(rs.getString("VALOR"));
				
				if(comparendo.getCobroCoactivo().equals("S"))
					comparendo.setCobroCoactivoChk(true);
			return comparendo;
		}
    }

	
	 // ---- BaseQueryOperation for Mapping ResultSet values --------------
	abstract class ValidarDocumentoOperation extends MappingSqlQuery {
		public ValidarDocumentoOperation(DataSource ds,String sql) {
	   		super(ds,sql);
		}	
		protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
			
				String existe = rs.getString("EXISTE");
			return existe;
		}
   }

	
    // ---- BaseQueryOperation for Mapping ResultSet values --------------
	abstract class ListaInfracionesQueryOperation extends MappingSqlQuery {
		public ListaInfracionesQueryOperation(DataSource ds,String sql) {
	   		super(ds,sql);
		}	
		protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
				ArrayList typeValueList = new ArrayList();
				String registro[] = {"0","0"};
				registro[0]= rs.getString("ID");
				registro[1]= rs.getString("VALOR");
				typeValueList.add(registro);
				registro = null;
			return typeValueList;
		}
    }
    // ------------- FindByPrimaryKeyQuery -------------------------------
    class FindByPrimaryKeyQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + "1=1";
    	public FindByPrimaryKeyQuery(DataSource ds) {
    		super(ds,sql);
			compile();
    	}
    	public Comparendo runQuery(long id) {
			List result =  execute( new Object[]{new Long(id)});
			if ( result.size() > 0 ) {
        		return (Comparendo) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindByCriteriaQuery ---------------------------------    
    class FindByCriteriaQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + " 1=1 ";
			//For required criteria elements uncomment required values
			  	  	  					//+ " AND ID = ? "
			  	  	  					//+ " AND ID_COMPARENDO_ENTIDAD = ? "
			  	  	  					//+ " AND ID_TIPO_INFRACCION = ? "
			  	  	  					//+ " AND ID_TIPO_INFRACTOR = ? "
			  	  	  					//+ " AND ID_PERSONA = ? "
			  	  	  					//+ " AND ID_CITACION = ? "
			  	  	  					//+ " AND CODIGO = ? "
			  	  	  					//+ " AND RADICADO = ? "
			  	  	  					//+ " AND DIRECCION = ? "
			  	  	  					//+ " AND CODIGO_BARRIO = ? "
			  	  	  					//+ " AND BARRIO = ? "
			  	  	  					//+ " AND CODIGO_COMUNA = ? "
			  	  	  					//+ " AND COMUNA = ? "
			  	  	  					//+ " AND COBRO_COACTIVO = ? "
			  	  	  					//+ " AND VALOR_COBRO = ? "
			  	  	  					//+ " AND ESTADO = ? "
			  	  	  					//+ " AND USUARIO_CREA = ? "
			  	  	  					//+ " AND FECHA_CREA = ? "
			  	  	  					//+ " AND USUARIO_MODIFICA = ? "
			  	  	  					//+ " AND FECHA_MODIFICA = ? "
										//+ "";
    	public FindByCriteriaQuery(DataSource ds) {
    		super(ds,sql);
    		//For required criteria elements uncomment required values
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.DATE) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.DATE) );
			compile();
    	}
    	public Comparendo runQuery(Comparendo comparendo) {
			List result =  execute( new Object[]{
			//For required criteria elements uncomment required values
				//comparendo.getId(),
				//comparendo.getIdComparendoEntidad(),
				//comparendo.getIdTipoInfraccion(),
				//comparendo.getIdTipoInfractor(),
				//comparendo.getIdPersona(),
				//comparendo.getIdCitacion(),
				//comparendo.getCodigo(),
				//comparendo.getRadicado(),
				//comparendo.getDireccion(),
				//comparendo.getCodigoBarrio(),
				//comparendo.getBarrio(),
				//comparendo.getCodigoComuna(),
				//comparendo.getComuna(),
				//comparendo.getCobroCoactivo(),
				//comparendo.getValorCobro(),
				//comparendo.getEstado(),
				//comparendo.getUsuarioCrea(),
				//comparendo.getFechaCrea(),
				//comparendo.getUsuarioModifica(),
				//comparendo.getFechaModifica(),
				});
			if ( result.size() > 0 ) {
        		return (Comparendo) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindAllQuery ----------------------------------------    
    class FindAllQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + " 1=1 ";
    	public FindAllQuery(DataSource ds) {
    		super(ds,sql);
			compile();
    	}
    	public List runQuery() {
			List result =  execute();
			if ( result.size() > 0 ) {
        		return  result;
        	} else {
        		return null;
        	}
    	}
    }
    
    // ------------- FindAllQuery ----------------------------------------    
    class FindByRadicadoQuery extends BaseQueryOperation {
		private static final String sql = "SELECT COMP.*,IDENTIFICACION,ID_TIPO_IDENTIFICACION,MAE1.VRT_NOMBRE AS COM_ENTIDAD, "
										+ " MAE2.VRT_NOMBRE AS INFRACTOR,VALOR FROM OPE_COMPARENDO_T COMP INNER JOIN "
										+ " ADM_PERSONA_T PER ON COMP.ID_PERSONA=PER.ID INNER JOIN "
										+ " ADM_VALOR_TIPO_MAESTRA_T MAE1 ON COMP.ID_COMPARENDO_ENTIDAD = MAE1.ID_VALOR_TIPO INNER JOIN "              
										+ " ADM_VALOR_TIPO_MAESTRA_T MAE2 ON COMP.ID_TIPO_INFRACTOR = MAE2.ID_VALOR_TIPO INNER JOIN "
										+ " OPE_TIPO_INFRACCION_T TI ON COMP.ID_TIPO_INFRACCION = TI.ID "
										+ " WHERE COMP.RADICADO=? OR '%' = ?"; 
    	public FindByRadicadoQuery(DataSource ds) {
    		super(ds,sql);
    		declareParameter( new SqlParameter(Types.CHAR) );
    		declareParameter( new SqlParameter(Types.CHAR) );
			compile();
    	}
    	public List runQuery(Comparendo comparendo) {
			List result =  execute( new Object[]{
					comparendo.getRadicado(),
					comparendo.getRadicado()
			});
			if ( result.size() > 0 ) {
        		return  result;
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindByActiveStateQuery  -----------------------------
    class FindByActiveStateQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + "1=1";
    	public FindByActiveStateQuery(DataSource ds) {
    		super(ds,sql);
			compile();
    	}
    	public Comparendo runQuery(Comparendo comparendo) {
			List result =  execute( new Object[]{
			});
			if ( result.size() > 0 ) {
        		return (Comparendo) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

    class ListaInfracciones extends ListaInfracionesQueryOperation{
		private static final String sql = "SELECT ID,VALOR FROM OPE_TIPO_INFRACCION_T ";
		public ListaInfracciones(DataSource ds) {
					super(ds,sql);
					compile();
		}
		public List runQuery() {
				List result =  execute();
				if ( result.size() > 0 ) {
					return result;
				} else {
					return null;
				}
		}
}
    
    
    // ------------- FindByDocumentoQuery ----------------------------------------    
    class VerificarDocumentoQuery extends ValidarDocumentoOperation {
		private static final String sql = "SELECT COALESCE(COUNT(*),0) AS EXISTE  " +
											" FROM ADM_PERSONA_T WHERE IDENTIFICACION =? AND "
										 	+ " ID_TIPO_IDENTIFICACION=? ";
										 
    	public VerificarDocumentoQuery(DataSource ds) {
    		super(ds,sql);			
			declareParameter( new SqlParameter(Types.CHAR) );
			declareParameter( new SqlParameter(Types.CHAR) );
			compile();
    	}
    	public String runQuery(Comparendo comparendo) {
			List result =  execute( new Object[]{							
					comparendo.getDocumento(),
					comparendo.getIdTipoDocumentoStr()
			});
			if ( result.size() > 0 ) {
        		return  result.get(0).toString();
        	} else {
        		return null;
        	}
    	}
    }  
    
}
